package com.example.zsydb.repository;
import com.example.zsydb.entity.GtlyResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import java.util.ArrayList;
import java.util.List;

@Repository
public class CustomGtlyResultRepository {

    private final JdbcTemplate jdbcTemplate;

    @Autowired
    public CustomGtlyResultRepository(
            @Qualifier("resultJdbcTemplate") JdbcTemplate resultJdbcTemplate) {
        this.jdbcTemplate = resultJdbcTemplate;
    }

    public List<GtlyResult> findByCriteria(String jh, String km, String csrqStr, String dm) {
        String sql = "SELECT * FROM GSFW_GTLY_RESULT WHERE 1=1";

        // 动态构建查询条件
        List<Object> params = new ArrayList<>();

        if (jh != null && !jh.isEmpty()) {
            sql += " AND JH = ?";
            params.add(jh);
        }
        if (km != null && !km.trim().isEmpty()) {
            sql += " AND KM = ?";
            params.add(km);
        }
        if (csrqStr != null && !csrqStr.isEmpty()) {
            // 使用时间范围查询（精确到分钟）
            sql += " AND CSRQ >= TO_TIMESTAMP(?, 'YYYY-MM-DD') " +
                    " AND CSRQ < TO_TIMESTAMP(?, 'YYYY-MM-DD') + INTERVAL '1' DAY";
            params.add(csrqStr);
            params.add(csrqStr);
        }
        if (dm != null && !dm.isEmpty()) {
            sql += " AND DM = ?";
            params.add(dm);
        }

        // 添加排序功能：按CSRQ降序排列（最新的在前）
        sql += " ORDER BY CSRQ DESC";

        // 使用 BeanPropertyRowMapper 自动映射所有字段
        return jdbcTemplate.query(
                sql,
                params.toArray(),
                new BeanPropertyRowMapper<>(GtlyResult.class)
        );
    }
}
